import { getFormModelKeyData } from './hyform'
import { getBtnOperator } from './hylist'
import { getDefaultOpenVal, submitDealReq } from './auth'
import { getBtnDefVal, getOperatorDefVal } from './hyopen'
import { getRemoteUrlParam, getCommonRemoteUrlVerify } from '@/utils/hyurl'
import { getTplKeyObj } from './hyctr'

export function getGlobalParam(thisObj) {
  return Object.assign({}, thisObj.uiPageUrl, thisObj.openParam, thisObj.initData, thisObj.formModel, thisObj.globalData.clickRow)
}
export function executeSubmitForm(thisObj, btnItem, globalData) {
  const formKeyData = getFormModelKeyData(thisObj)
  let operatorDefVal = {}
  const defVal = getBtnDefVal(thisObj, btnItem)
  let urlKey = ''
  const operator = getBtnOperator(thisObj, globalData, btnItem)
  if (operator != null) {
    urlKey = operator.s_REF_URL_KEY
    operatorDefVal = getOperatorDefVal(thisObj, operator.refSetOpenVal)
  } else {
    thisObj.$message.success('不满足配置规则')
    return
  }
  let postParam = getRemoteUrlParam(thisObj, urlKey, globalData)
  postParam = Object.assign(postParam, defVal, operatorDefVal)
  const verify = getCommonRemoteUrlVerify(thisObj, urlKey, postParam)
  if (verify === 1) {
    // 查询验证未通过
    return
  }
  let title = operator.s_PRE_TIP_TITLE
  if (!title) {
    title = '确认操作'
  }
  let tipContent = '确认保存表单的数据?'
  if (globalData.formModel && operator.s_PRE_TIP_KEY) {
    if (globalData.formModel[operator.s_PRE_TIP_KEY]) {
      tipContent = '确认保存[' + globalData.formModel[operator.s_PRE_TIP_KEY] + ']数据?'
    }
  }
  thisObj.$confirm({
    title: title,
    content: tipContent,
    onOk: function() {
      console.log('execute postParam', postParam)
      thisObj.loading = true
      submitDealReq(postParam).then((res) => {
        thisObj.loading = false
        if (res.data.success) {
          thisObj.$message.success(res.data.message)
          thisObj.$emit('reloadLoadData', thisObj.triggerOpenParam.openBtnItem, res.data, urlKey, formKeyData)
          thisObj.visible = false

          thisObj.clearData()
          thisObj.$emit('close')
        } else {
          console.log('提交异常结果', res.data)
          thisObj.$message.warning(res.data.message)
          thisObj.handleVerifyError(res.data)
        }
      }).catch(r => {
        thisObj.$message.warning(r)
        thisObj.loading = false
      })
    }
  })
}

export function executeRecord(thisObj, btnItem, globalData) {
  const defVal = getBtnDefVal(thisObj, btnItem)
  if (globalData.clickSrc === 'toolbarClick') {
    if (btnItem.mutiBtn === 2) { // 多选操作，没选择提醒
      if (globalData.tableSelectedRow === undefined || globalData.tableSelectedRow.length === 0) {
        thisObj.$message.warning(thisObj.$t('tips.noDataSelected'))
        return
      }
    }
    let tmpData = null
    tmpData = getCheckRecordKeyStr(globalData.tableSelectedRow)
    globalData.clickRow = tmpData
    console.log('选中记录信息#', tmpData)
  }
  let urlKey = ''
  let operatorDefVal = {}
  const operator = getBtnOperator(thisObj, globalData, btnItem)
  if (operator != null) {
    urlKey = operator.s_REF_URL_KEY
    operatorDefVal = getOperatorDefVal(thisObj, operator.refSetOpenVal)
  } else {
    thisObj.$message.success('不满足配置规则')
    return
  }
  let postParam = getRemoteUrlParam(thisObj, urlKey, globalData)
  postParam = Object.assign(postParam, defVal, operatorDefVal)
  const verify = getCommonRemoteUrlVerify(thisObj, urlKey, postParam)
  if (verify === 1) {
    // 查询验证未通过
    return
  }
  let title = operator.s_PRE_TIP_TITLE
  if (!title) {
    title = '确认操作'
  }
  let tipContent = '确定要操作所选中的数据?'
  if (globalData.checkRow && operator.s_PRE_TIP_KEY) {
    if (globalData.checkRow[operator.s_PRE_TIP_KEY]) {
      tipContent = '确定要操作所选中的[' + globalData.checkRow[operator.s_PRE_TIP_KEY] + ']数据?'
    }
  }
  thisObj.$confirm({
    title: title,
    content: tipContent,
    onOk: function() {
      thisObj.loading = true
      submitDealReq(postParam).then((res) => {
        thisObj.loading = false
        if (res.data.success) {
          if (operator.s_RESULT_TIP_TITLE !== undefined) {
            thisObj.$message.success(operator.s_RESULT_TIP_TITLE)
          } else {
            thisObj.$message.success(res.data.resultMsg)
            // thisObj.$message.success(thisObj.$t('tips.executeSuccess'))
          }
          thisObj.search(null)
        } else {
          thisObj.$message.warning(res.data.resultMsg)
        }
      }).catch(r => {
        console.log(r)
        thisObj.$message.warning(r)
        thisObj.loading = false
      })
    }
  })
}
/**
 * 删除数据
 * @param thisObj
 * @param globalData
 */
export function deleteRemoteRecord(thisObj, globalData) {
  let urlKey = ''
  const btnItem = globalData.clickItem
  const defVal = getBtnDefVal(thisObj, btnItem)
  const operator = getBtnOperator(thisObj, globalData, btnItem)
  console.log('globalData.clickItem', globalData.clickItem)
  console.log('operator', operator, globalData)
  let operatorDefVal = {}
  if (operator != null) {
    urlKey = operator.s_REF_URL_KEY
    operatorDefVal = getOperatorDefVal(thisObj, operator.refSetOpenVal)
  } else {
    thisObj.$message.success('不满足配置规则')
    return
  }
  let postParam = getRemoteUrlParam(thisObj, urlKey, globalData)
  postParam = Object.assign(postParam, defVal, operatorDefVal)
  const verify = getCommonRemoteUrlVerify(thisObj, urlKey, postParam)
  if (verify === 1) {
    // 查询验证未通过
    return
  }
  let title = operator.s_PRE_TIP_TITLE
  if (!title) {
    title = '确认操作'
  }
  let tipContent = '确认删除当前数据?'
  if (globalData.clickRow && operator.s_PRE_TIP_KEY) {
    if (globalData.clickRow[operator.s_PRE_TIP_KEY]) {
      tipContent = '确认删除[' + globalData.clickRow[operator.s_PRE_TIP_KEY] + ']数据?'
    }
  }
  thisObj.$confirm({
    title: title,
    content: tipContent,
    onOk: function() {
      thisObj.loading = true
      submitDealReq(postParam).then((res) => {
        thisObj.loading = false
        if (res.data.success) {
          thisObj.$message.success(res.data.message)
          console.log('deleteSuccess')
          thisObj.deleteSuccess(btnItem, res.data, 'delete', globalData.clickRow)
        } else {
          console.log('删除异常结果', res.data)
          thisObj.$message.warning(res.data.message)
          thisObj.handleVerifyError(res.data)
        }
      }).catch(r => {
        console.log('r', r)
        thisObj.$message.warning(r)
        thisObj.loading = false
      })
    }
  })
}
export function getCheckRecordParam(thisObj, btnItem, record) {
  const tmpData = {}
  let refSetOpenVal = btnItem.refSetOpenVal
  if (refSetOpenVal === undefined) {
    refSetOpenVal = getDefaultOpenVal(thisObj)
  }
  getCheckRecordObj(record, refSetOpenVal, tmpData)
  const newTmp = {}
  for (const i in tmpData) {
    newTmp[i] = tmpData[i].join()
  }
  newTmp.item = newTmp
  return newTmp
}

export function getRecordRefSetOpenVal(record) {
  const refSetOpenVal = []
  for (const key in record) {
    const setValObj = {}
    setValObj.key = key
    setValObj.val = key
    refSetOpenVal.push(setValObj)
  }
  return refSetOpenVal
}

/**
 * 选中数据
 * @param recordArray
 */
export function getCheckRecordKeyArr(recordArray) {
  const mergeObj = {}
  const firstRecord = recordArray[0]
  const refSetOpenVal = getRecordRefSetOpenVal(firstRecord)
  return getCheckRecordObj(recordArray, refSetOpenVal, mergeObj)
}

/**
 * 选中数据
 * @param recordArray
 */
export function getCheckRecordKeyStr(recordArray) {
  const mergeObjStr = {}
  const mergeObj = {}
  if (recordArray === undefined) {
    return mergeObjStr
  }
  const firstRecord = recordArray[0]
  const refSetOpenVal = getRecordRefSetOpenVal(firstRecord)
  getCheckRecordObj(recordArray, refSetOpenVal, mergeObj)
  for (const key in mergeObj) {
    if (mergeObj[key].length === 1) {
      mergeObjStr[key] = mergeObj[key][0]
    } else if (mergeObj[key].length > 1) {
      mergeObjStr[key] = mergeObj[key].join()
    } else {
      // 避免返回单条记录时,相关字段类型都变成字符串
      mergeObjStr[key] = mergeObj[key]
    }
  }
  return mergeObjStr
}

export function getCheckRecordObj(record, refSetOpenVal, mergeObj) {
  record.forEach((j) => {
    for (const idx in refSetOpenVal) {
      const setValObj = refSetOpenVal[idx]
      const key = setValObj.key
      const val = setValObj.val
      const c = j[val]
      if (mergeObj[key] !== undefined) {
        mergeObj[key].push(c)
      } else {
        const tmpArr = []
        tmpArr.push(c)
        mergeObj[key] = tmpArr
      }
    }
  })
  while (record.children !== undefined) {
    for (const i in record.children) {
      const tmp = record.children[i]
      this.getCheckRecordObj(tmp, refSetOpenVal, mergeObj)
    }
  }
}

/**
 * 批量删除数据
 * @param thisObj
 * @param globalData
 */
export function deleteBatchRemoteRecord(thisObj, globalData) {
  const clickRow = getCheckRecordKeyStr(globalData.tableSelectedRow)
  const batchGlobalData = Object.assign({}, globalData)
  // thisObj.globalData.clickRow = clickRow
  // thisObj.globalData.globalParam = getGlobalParam(thisObj)
  batchGlobalData.clickRow = clickRow
  batchGlobalData.globalParam = getGlobalParam(thisObj)
  console.log('batch remote', thisObj.globalData)
  deleteRemoteRecord(thisObj, thisObj.globalData)
  thisObj.tableSelectedRow = []
  thisObj.tableSelectedKey = []
}

export function deleteBatchLocalList(thisObj, globalData) {
  console.log('globalData', globalData)
  const newRows = []
  const tableData = thisObj.tableData
  let newRowId = 0
  for (const i in tableData) {
    const row = tableData[i]
    let hasDeleteRow = false
    for (const rowIdx in globalData.tableSelectedRow) {
      const deleteRow = globalData.tableSelectedRow[rowIdx]
      if (deleteRow.rowId === row.rowId) {
        hasDeleteRow = true
        break
      }
    }
    if (!hasDeleteRow) {
      newRowId = newRowId + 1
      row.rowId = newRowId
      newRows.push(row)
    }
  }
  thisObj.tableData = newRows
  thisObj.tablePagination.total = newRows.length
  thisObj.tableSelectedRow = []
  thisObj.tableSelectedKey = []
}

export function deleteLocalList(thisObj, globalData) {
  const newRows = []
  const deleteRow = globalData.clickRow
  const tableData = thisObj.tableData
  let newRowId = 0
  for (const i in tableData) {
    const row = tableData[i]
    if (deleteRow.rowId !== row.rowId) {
      newRowId = newRowId + 1
      row.rowId = newRowId
      newRows.push(row)
    }
  }
  thisObj.tableData = newRows
  thisObj.tablePagination.total = newRows.length
}

export function localList(selectionRows, formItem, thisObj) {
  const newRows = []
  if (selectionRows.length !== 0) {
    const tableId = formItem.tableId
    const tplObj = getTplKeyObj(thisObj, tableId)
    for (const i in selectionRows) {
      const row = selectionRows[i]
      row.hyLocalTmpData = 'hyLocalTmpData'
      row.rowId = Number(i) + 1
      newRows.push(row)
    }
    const newRowIdx = selectionRows.length
    if (tplObj.tableData !== undefined) {
      for (const i in tplObj.tableData) {
        const row = tplObj.tableData[i]
        row.rowId = Number(newRowIdx) + Number(i) + 1
        newRows.push(row)
      }
    }
  }
  return newRows
}

/**
 * @param selectionRows
 * @param formItem
 * @param _thisObj
 */
export function getQuickSetLocalListData(selectionRows, formItem, _thisObj) {
  const tableId = formItem.tableId
  const tplObj = getTplKeyObj(_thisObj, tableId)
  const rowsList = localList(selectionRows, formItem, _thisObj)
  tplObj.tableData = rowsList
  _thisObj.globalData[tableId] = rowsList
  tplObj.tablePagination.total = tplObj.tableData.length
}

/**
 * @param selectionRows
 * @param formItem
 * @param _thisObj
 */
export function getQuickSetLocalTreeData(selectionRows, formItem, _thisObj) {
  const tableId = formItem.tableId
  const tplObj = getTplKeyObj(_thisObj, tableId)
  tplObj.tableData = localList(selectionRows, formItem, _thisObj)
}
// /**
//  * 过期
//  * @param thisObj
//  * @param btnItem
//  */
// export function batchDeleteRecord(thisObj, btnItem) {
//   if (!thisObj.tableSelectedRow.length) {
//     thisObj.$message.warning(thisObj.$t('tips.noDataSelected'))
//     return
//   }
//   const rowIds = []
//   const rowTipData = []
//   const record = {}
//   thisObj.tableSelectedRow.forEach((j) => {
//     rowIds.push(j[thisObj.tableRowKey])
//     if (btnItem.tipKey) {
//       rowTipData.push(j[btnItem.tipKey])
//     }
//   })
//   console.log('batch del', rowIds.join())
//   if (btnItem.tipKey) {
//     record[btnItem.tipKey] = rowTipData.join()
//   }
//   record[thisObj.tableRowKey] = rowIds.join()
//   deleteRecord(thisObj, btnItem, rowIds.join(), record)
// }
//
// /**
//  * 过期
//  * @param thisObj
//  * @param btnItem
//  * @param rowIds
//  * @param record
//  */
// export function deleteRecord(thisObj, btnItem, rowIds, record) {
//   const urlKey = btnItem.urlKey
//   const tempParam = getRemoteUrlParam(thisObj, urlKey, record)
//   let param = {}
//   param = Object.assign({}, param, tempParam)
//   let title = btnItem.title
//   if (!title) {
//     title = '确认操作'
//   }
//   let tipContent = '确定要操作所选中的数据?'
//   if (btnItem.tipKey && btnItem.tipKey != null) {
//     if (record && record[btnItem.tipKey]) {
//       tipContent = '确定要操作所选中的[' + record[btnItem.tipKey] + ']数据?'
//     }
//   }
//   thisObj.$confirm({
//     title: title,
//     content: tipContent,
//     onOk: function() {
//       thisObj.loading = true
//       submitDealReq(param).then((res) => {
//         thisObj.loading = false
//         if (res.data.success) {
//           thisObj.deleteSuccess(btnItem, rowIds, record)
//         } else {
//           thisObj.$message.warning(res.data.message)
//         }
//       }).catch(reason => {
//         thisObj.loading = false
//         console.error('reason' + reason)
//       })
//     }
//   })
// }
